package cn.com.anysdk.map.factory;

import cn.com.anysdk.map.config.*;
import cn.com.anysdk.map.exception.MapConfigException;
import cn.com.anysdk.map.service.*;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;

/**
 * 地图服务工厂类
 */
public class MapServiceFactory {
    
    /**
     * 创建地图服务实例
     *
     * @param config 地图配置
     * @return 地图服务实例
     * @throws MapConfigException 配置异常
     */
    public static MapService createMapService(MapConfig config) {
        if (config == null) {
            throw new MapConfigException("MapConfig cannot be null");
        }
        
        if (!config.isEnabled()) {
            throw new MapConfigException("Map service is disabled");
        }

        return switch (config.getType()) {
            case BAIDU -> {
                if (!(config instanceof BaiduMapConfig)) {
                    throw new MapConfigException("Invalid config type for Baidu Map");
                }
                CloseableHttpClient httpClient = createHttpClient(config);
                yield new BaiduMapService((BaiduMapConfig) config, httpClient);
            }
            case AMAP -> {
                if (!(config instanceof AmapConfig)) {
                    throw new MapConfigException("Invalid config type for Amap");
                }
                CloseableHttpClient httpClient = createHttpClient(config);
                yield new AmapService((AmapConfig) config, httpClient);
            }
            case MOCK -> new MockService();
            default -> throw new MapConfigException("Unsupported map provider type: " + config.getType());
        };
    }

    /**
     * 创建 HTTP 客户端
     *
     * @param config 地图配置
     * @return HTTP 客户端
     */
    private static CloseableHttpClient createHttpClient(MapConfig config) {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(100);
        connectionManager.setDefaultMaxPerRoute(20);

        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(org.apache.hc.client5.http.config.RequestConfig.custom()
                        .setResponseTimeout(config.getTimeout())
                        .build())
                .build();
    }
}
